/** 
 * @memo 简化创建Ext-chart方法 
 * @author lic
 * @sample 粘贴用
 * @method
 * @param 图形id：this.id+"_chart"	
 * @param xtype:'xchart'
 *	
 *粘贴用
 	new Ext.ux.ChartPanel({
       id:'',					
       width:,
       height:,
       //renderTo: '',					
       title:'',				
       chartTitle:'',
       form:,						
       chartTool:'',
       swf:'',					
       key:'',						
       params:{}
    });
 *
 * 创建示例
 	new Ext.ux.ChartPanel({
       id:'chartpanel',					//必需
       width:500,
       height:300,
       renderTo: 'tu1',					//渲染目标节点
       title:"单个图测试",				//panel标题
       chartTitle:"固定生产总值比例分析",//图形标题
       form:form,						//查询用的form绑定
       chartTool:'grid|save|print|order',//图形工具栏(可选参数,多个以竖线分隔)
       swf:'Pie2D.swf',					//flash名称，默认路径：/webContent/charts/fusionSwf/
       exactFit:true,					//让图形自动匹配外层容器大小.当设为true时需要将图形的labelDisplay设为none,STAGGER or ROTATE.
       key:'sql1',						//XMl文件名称,默认路径: /webContent/chartsdata/或者/webContent/chartsdata/下的文件夹中
       params:{zhibiao:'gongyezengjiazhi'}//参数，与出图sql语句中的参数对应
    });
    
 	update(config) 		更新图
 	
 	例: 
 	update({
 		key:'',
 		swf:'',
 		params:{}
 	});
 	
 	reload()			  刷新图形,当绑定form时,自动从form取出参数设置到params
 	setChartTitle(title)  设置图形标题
 	setKey(key,[lazy])  重新设置key,lazy:是否立刻刷新,传true/false,默认false立刻刷新,当rendered为false时强制为true
 	setSwf(swf,[lazy])  重新设置swf文件,lazy:是否立刻刷新,传true/false,默认false立刻刷新,当rendered为false时强制为true
 	setParams(config,[init],[lazy])   重新设置参数,config格式为json对象,例如:{year:2005},init:是否进行初始化,初始化会清除原有参数,传true/false,默认false不清除,lazy:是否立刻刷新,传true/false,默认false立刻刷新,当rendered为false时强制为true
	showXML() 			  查看当前与图形绑定的xml文件
	modifyXML()			  修改xml配置
	showMask()			  显示遮罩
	hideMask()			  隐藏遮罩
	enlarge()			  放大图形
	setTools(tools)			  重新配置工具栏,例如传入:'grid|save|print|order'
*/
 
Ext.ux.ChartPanel = Ext.extend(Ext.Panel, {
    data_xml: '',
    initFlag:false,
    isActive:false,
    isUpdate:false,
    initComponent : function(){
   	  Ext.ux.ChartPanel.superclass.initComponent.call(this);
        this.chart = new FusionCharts(getRootPath()+'/charts/fusionSwf/'+this.swf, this.id+"_chart", "100%", "100%", "0", "1", "FFFFFF",this.exactFit?'exactFit':null);
        this.chart.addParam("wmode","transparent");
    },
    afterRender : function(){
    	
    	if(!this.initFlag){
    		this.initFlag=true;
    		this.isActive=true;
	    	Ext.ux.ChartPanel.superclass.afterRender.call(this);
			this.mask=new Ext.LoadMask(this.body, {msg:"请等待..."});
			//添加图形DIV布局
			this.appendChartTitleFrame();
			//添加图形标题
			if(this.chartTitle)
			{
				this.setChartTitle(this.chartTitle);
			}
			//添加图形工具栏
			if(this.chartTool)
			{
				toolbars = this.chartTool.split('|');
				//单序列转换
				if(this.needConvert&&(this.swf=='Column2D.swf' || this.swf=='Column3D.swf' || this.swf=='Pie2D.swf' || this.swf=='Pie3D.swf' || this.swf=='Line.swf' || this.swf=='Doughnut2D.swf' || this.swf=='Doughnut3D.swf' || this.swf=='Pyramid.swf'))
					toolbars.push('convertSingle');
				//多序列转换
				if(this.needConvert&&(this.swf=='MSColumn2D.swf' || this.swf=='MSColumn3D.swf' || this.swf=='MSLine.swf'))
					toolbars.push('convertMultiple');
				//Scroll图形转换
				if(this.needConvert&&(this.swf=='ScrollLine2D.swf' || this.swf=='ScrollColumn2D.swf'))
					toolbars.push('convertScroll');
				if(this.sortItems)
					toolbars.push('sort');
		    	if(this.isMax)
		    		toolbars.push('min');
		    	else
		    		toolbars.push('max');
				for(var i=0,len = toolbars.length;i < len;i++)
				{
					this.setChartTool(toolbars[i],this);
				}
			}
			//添加图形容器DIV
			var divNode = document.createElement('div');
			divNode.id = this.body.id+"_chart_tu";
			if(this.chartTitle||this.chartTool)
			{
				 divNode.height = "92%";
				 this.chart.setAttribute('height', "93%");
			}
			else 
			{
				 divNode.height = "100%";
			}
			this.body.dom.appendChild(divNode);
			this.loadChartXml(this,true);
			this.showMask();
			//this.on('resize', function(){this.chart.initialDataSet=false;this.chart.render(this.body.id);if(this.chartTitle)this.appendChartTitle(this)});
    	}
	 },
	 //private
	 appendChartTitleFrame:function()
	 {
		 var divNode;
		 if(this.chartTitle||this.chartTool)
		 {
			 divNode = document.createElement('div');
			 divNode.id = this.body.id+"_chart_div";
			 if(this.frame)
			 {
				 divNode.className = "x-panel-chart-div-frame";
			 }
			 else 
			 {
				 divNode.className = "x-panel-chart-div";
			 }
			 //创建图形标题DIV
			 var chartTitleDiv = document.createElement('div');
			 chartTitleDiv.id = this.body.id+"_tit";
			 chartTitleDiv.className = "x-panel-chart-div-title";
			 divNode.appendChild(chartTitleDiv);
			 //创建图形工具栏DIV
			 var chartToolDiv = document.createElement('div');
			 chartToolDiv.id = this.body.id+"_chart_tools";
			 chartToolDiv.className = "x-panel-chart-div-tools";
			 divNode.appendChild(chartToolDiv);
			 var pNode = this.body.dom;
			 if (pNode.hasChildNodes) pNode.insertBefore(divNode, pNode.firstChild);
			 else pNode.appendChild(divNode);
		 }
	 },
	setChartTitle:function(chartTit)
	{
		 this.chartTitle = chartTit;
		 if(this.body == null)
		 {//如果图形panel还没初始化，只需给chartTitle赋值
			 return false;
		 }
		 var chartTitleDiv = document.getElementById(this.body.id+"_tit");
		 if(chartTit == null||chartTit.trim() == "")
		 {
			 if(chartTitleDiv != null)
			 {
				 chartTitleDiv.innerHTML = "";
			 }
		 }
		 else 
		 {
			 if(chartTitleDiv != null)
			 {
				 chartTitleDiv.innerHTML = this.chartTitle;
			 }
			 else 
			 {
				 //TODO
				 this.appendChartTitleFrame();
				 document.getElementById(this.body.id+"_tit").innerHTML = this.chartTitle;
				 document.getElementById(this.body.id+"_chart_tu").height = "92%";
				 this.chart.setAttribute('height', "90%");
				 this.reload();
			 }
			 if(Constant_System_IsDevelop)
				{
					var p = this;
					if(chartTitleDiv != null) 
					{
						//查看图形XML
						var viewXml_ = document.createElement('a');
						viewXml_.href = "#";
						viewXml_.onclick = function(){Ext.getCmp(p.id).showXML();};
						viewXml_.innerText = "X";
						viewXml_.style.color = "red";
						viewXml_["ext:qtip"] = "查看XML";
						chartTitleDiv.appendChild(viewXml_);
						//修改图形
						var modifyXml_ = document.createElement('a');
						modifyXml_.href = "#";
						modifyXml_.onclick = function(){Ext.getCmp(p.id).modifyXML();};
						modifyXml_.innerText = "S";
						modifyXml_.style.color = "red";
						modifyXml_["ext:qtip"] = "修改图形";
						chartTitleDiv.appendChild(modifyXml_);
						//刷新图形
						var reloadXml_ = document.createElement('a');
						reloadXml_.href = "#";
						reloadXml_.onclick = function(){Ext.getCmp(p.id).reload();};
						reloadXml_.innerText = "R";
						reloadXml_.style.color = "red";
						reloadXml_["ext:qtip"] = "刷新图形";
						chartTitleDiv.appendChild(reloadXml_);
					}
				}
		 }
	},
	setChartTool:function(type,scope)
	{
		var chartToolDiv = document.getElementById(scope.body.id+"_chart_tools");
		switch(type){
			case 'grid':
				var  imgGrid = document.createElement('img');
				imgGrid.style.cursor = 'pointer';
				imgGrid.src = getRootPath()+"/images/icon/binlan_1.gif";
				imgGrid.onmouseover = function(){imgGrid.src = getRootPath()+"/images/icon/binlan_2.gif"};
				imgGrid.onmouseout = function(){imgGrid.src = getRootPath()+"/images/icon/binlan_1.gif"};
				imgGrid.onclick = function(){convert2table(scope.body.id,scope.id+"_chart");};
			 	imgGrid['ext:qtip'] = "图形数据";
				chartToolDiv.appendChild(imgGrid);
			 	break;
			 case 'save':
				var  imgSave = document.createElement('img');
				imgSave.style.cursor = 'pointer';
				imgSave.src = getRootPath()+"/images/icon/saveimg_1.gif";
				imgSave.onmouseover = function(){imgSave.src = getRootPath()+"/images/icon/saveimg_2.gif"};
				imgSave.onmouseout = function(){imgSave.src = getRootPath()+"/images/icon/saveimg_1.gif"};
				imgSave.onclick = function(){exportCharts(scope.id+"_chart",'JPG',scope.body.id);};
				imgSave['ext:qtip'] = "保存图形";
				chartToolDiv.appendChild(imgSave); 
			 	break;
			 case 'print':
				var  imgPrint = document.createElement('img');
				imgPrint.id="printImg";
				imgPrint.style.cursor = 'pointer';
				imgPrint.src = getRootPath()+"/images/icon/print_1.gif";
				imgPrint.onmouseover = function(){imgPrint.src = getRootPath()+"/images/icon/print_2.gif"};
				imgPrint.onmouseout = function(){imgPrint.src = getRootPath()+"/images/icon/print_1.gif"};
				imgPrint.onclick = function(){printChart(scope.id+"_chart");};
				imgPrint['ext:qtip'] = "打印图形";
				chartToolDiv.appendChild(imgPrint); 
			 	break;
			 case 'order':
			 case 'sort' :
				 var  imgConvert = document.createElement('img');
				 imgConvert.id="sortImg";
				 imgConvert.style.cursor = 'pointer';
				 imgConvert.src = getRootPath()+"/images/icon/order_asc_1.gif";
				 imgConvert['ext:qtip'] = "升序排列";
				 imgConvert.onmouseover = function()
				 {if(scope.sort==null){imgConvert.src = getRootPath()+"/images/icon/order_asc_2.gif";}else if(scope.sort=='asc'){imgConvert.src=getRootPath()+"/images/icon/order_desc_2.gif";}else {imgConvert.src=getRootPath()+"/images/icon/convert2.gif";} };
				 imgConvert.onmouseout = function(){if(scope.sort==null)imgConvert.src = getRootPath()+"/images/icon/order_asc_1.gif";else if(scope.sort=='asc')imgConvert.src=getRootPath()+"/images/icon/order_desc_1.gif";else imgConvert.src=getRootPath()+"/images/icon/convert1.gif";};
				 imgConvert.onclick = function(){if(scope.sort==null){imgConvert['ext:qtip'] = "降序排列";imgConvert.src = getRootPath()+"/images/icon/order_desc_2.gif";}else if(scope.sort=='asc'){imgConvert.src=getRootPath()+"/images/icon/convert2.gif";imgConvert['ext:qtip'] = "自然顺序";}else {imgConvert.src = getRootPath()+"/images/icon/order_asc_2.gif";imgConvert['ext:qtip'] = "升序排列";}sortChart(imgConvert,scope);}				 
				 chartToolDiv.appendChild(imgConvert); 
				 break;
			 case 'convertSingle': //单序列图形相互转化
			 case 'convertMultiple': //多序列图形相互转化
			 case 'convertScroll': //滚动图形相互转化
				 var  imgConvert = document.createElement('img');
				 imgConvert.style.cursor = 'pointer';
				 imgConvert.src = getRootPath()+"/images/icon/convert1.gif";
				 imgConvert.onmouseover = function(){imgConvert.src = getRootPath()+"/images/icon/convert2.gif"};
				 imgConvert.onmouseout = function(){imgConvert.src = getRootPath()+"/images/icon/convert1.gif"};
				 imgConvert.onclick = function(){convertChart(imgConvert,scope,type);};
				 imgConvert['ext:qtip'] = "图型转换";
				 chartToolDiv.appendChild(imgConvert); 
				 break;
			 case 'max':
				 var  imgMax = document.createElement('img');
				 imgMax.style.cursor = 'pointer';
				 imgMax.src = getRootPath()+"/images/icon/max_1.gif";
				 imgMax.onmouseover = function(){imgMax.src = getRootPath()+"/images/icon/max_2.gif"};
				 imgMax.onmouseout = function(){imgMax.src = getRootPath()+"/images/icon/max_1.gif"};
				 imgMax.onclick = function(){scope.enlarge(scope);};
				 imgMax['ext:qtip'] = "放大";
				 chartToolDiv.appendChild(imgMax); 
				 break;
			 case 'min':
				 var  imgMax = document.createElement('img');
				 imgMax.style.cursor = 'pointer';
				 imgMax.src = getRootPath()+"/images/icon/min_1.gif";
				 imgMax.onmouseover = function(){imgMax.src = getRootPath()+"/images/icon/min_2.gif"};
				 imgMax.onmouseout = function(){imgMax.src = getRootPath()+"/images/icon/min_1.gif"};
				 imgMax.onclick = function(){scope.enlarge(scope);};
				 imgMax['ext:qtip'] = "缩小";
				 chartToolDiv.appendChild(imgMax); 
				 break;
			 default:break;
		}
	},
    setSwf: function(swf,lazy){
     	if(!this.rendered)
    	  		lazy=true;
     	this.swf=swf;
        this.chart.setAttribute('swf', getRootPath()+'/charts/fusionSwf/'+swf+this.crack);
        if(lazy!=true && this.isActive){
        	 this.showMask();
    		 this.chart.initialDataSet=false;//关键
			 this.loadChartXml(this,true);
			 this.isUpdate=false;
		}else{
			 this.isUpdate=true;
		}
    },
    setKey: function(key,lazy){
    	  if(!this.rendered)
    	  		lazy=true;
        this.key=key;
        if(lazy!=true && this.isActive){
	          this.showMask();
			  this.loadChartXml(this);
			  this.isUpdate=false;
		}else{
			  this.isUpdate=true;
		}
    },
    setParams: function(config,init,lazy){
          if(!this.rendered)
    	  		lazy=true;
		  if(init)
		  		this.params={};
		  config=config||{};
		  Ext.apply(this.params,config);
		  if(lazy!=true && this.isActive){
			  this.loadChartXml(this);
			  this.isUpdate=false;
		  }else{
			  this.isUpdate=true;
		  }
    },
    update:function(config){
    	if(!this.rendered)
    		config.lazy=true;
		if(config.key)
			this.setKey(config.key,true);
		if(config.params)
			this.setParams(config.params,true,true);
		if(config.swf){
			if(config.lazy==true){
				this.setSwf(config.swf,true);
	     	}else{
	     		this.setSwf(config.swf);
	     	}
		}else{
    		if(config.lazy!=true && this.isActive){
    			this.showMask();
    			this.loadChartXml(this);
    			this.isUpdate=false;
     		}else{
     			this.isUpdate=true;
     		}
		}
    },
    reload:function(){
    	  if(this.rendered){
	    	  this.showMask();
			  this.loadChartXml(this);
		  }
    },
    loadChartXml:function(p,lazy)//内部方法
    {
    	p.params=p.params||{};
    	if(typeof(plcdataid)!="undefined"){ //页面设计器
	 		this.params.plcdataid=plcdataid;
	 		this.params.plcdatakey=p.key;
	 	}
		if(!isNull(this.form)){
			 var params=this.form.getForm().getValues();
			 function eachItem(item,index,length) {
				 if (item.isXType("xlovcombo")) {
					 if(item.getValue() != null && item.getValue().trim()!=''){
						 params[item.id] = item.getValue();
					 }else{
						 params[item.id] = null;
					 }
				 }
			 }   
			 this.form.items.each(eachItem); 
			 Ext.apply(this.params,params);
		}
    	p.params._chartId=p.key;
    	Ext.Ajax.request({
				url: getRootPath()+'/chart?decorate=no',
				method:"post",
				success:function(res){
					 p.data_xml=res.responseText;
					 p.chart.setDataXML(res.responseText);
					 if(lazy) p.chart.render(p.body.id+"_chart_tu");
					 p.hideMask();
				},
				params:p.params
		 });
    },
    showXML:function(){
    	 win=Ext.getCmp(this.id+'_win_xml');
    	 if(typeof(win)=='undefined')
	    	 win =  new Ext.Window({
	    	 		 id: this.id+'_win_xml',
					 width: 550,
					 height: 350,
					 closeAction:'hide',
					 plain: true,
					 layout: 'border',
					 maximizable:true,
					 items:[{
					 		xtype:'panel',
							region:'center',
							autoScroll:true,
							html: "<pre id='"+this.id+"_win_xml_content"+"'></pre>"
					 }]
			 });
		 win.setTitle(this.title+'查看xml数据');
		 win.show();
		 Ext.getDom(this.id+"_win_xml_content").innerText=this.data_xml;
    },
    modifyXML:function(){
	   	 win=Ext.getCmp(this.id+'_win_modify_xml');
		 if(typeof(win)=='undefined')
	    	 win =  new Ext.Window({
	    	 		 id: this.id+'_win_modify_xml',
					 closeAction:'hide',
					 plain: true,
					 maximizable:true,
					 width:500,
					 height:350
			 });
		 win.setTitle(this.title+'修改图形配置');
		 win.show();
		 win.maximize();
		 params={url:getRootPath()+"/chart?debug=true&decorate=no&chart_panel_id="+this.id+"&win_id="+this.id+'_win_modify_xml',params:this.params};
		 win.load(params);
		 win.reload=function(id){
		 	this.load(params);
		 };
	},
    showMask:function(){
    	 if(this.rendered){
    	 	this.mask.show();
    	 }
    },
    hideMask:function(){
    	 if(this.rendered){
	    	 this.mask.hide();
	    }
    },
    setTools:function(tools){
    	document.getElementById(this.body.id+"_chart_tools").innerHTML='';
    	var toolbars = tools.split('|');
    	if(this.isMax)
    		toolbars.push('min');
    	else
    		toolbars.push('max');
		for(var i=0,len = toolbars.length;i < len;i++)
		{
			this.setChartTool(toolbars[i],this);
		}
    },
    enlarge:function(p){
    	var win = Ext.getCmp('system_chart_max_win_');
    	if(p.isMax){
    		win.hide();
    		return;
    	}
    	if(!win){
    		win = new Ext.Window({
    			 id:'system_chart_max_win_',
    			 width: all_width,
    			 height: all_height+1,
    			 y:94,
    			 draggable:false,
    			 title:'全屏查看',
    			 closeAction:'hide',
    			 resizable:false,
    			 items:[new Ext.ux.ChartPanel({
    				 id:'system_chart_max_',
    				 width: all_width-10,
    				 height: all_height-15,
    			     title:p.title,				
    			     chartTitle:p.chartTitle,
    			     chartTool:p.chartTool,
    			     swf:p.swf,					
    			     key:p.key,						
    			     params:p.params,
    			     sortItems:p.sortItems,
    			     isMax:true
    			 })]
    		});
    	}else{
    		var chart = Ext.getCmp('system_chart_max_');
    		chart.setChartTitle(p.chartTitle);
    		chart.setTitle(p.title);
    		chart.setTools(p.chartTool.replace('max','min'));
    		chart.update({
    	 		key:p.key,
    	 		swf:p.swf,
    	 		params:p.params
    	 	});
    	}
    	win.show(Ext.getCmp(p.id).body.id+"_chart_div");
    },
	 onDestroy : function(){
	 	 delete this.data[this.body.id];
	 },
	 listeners:{
		 activate : function(o){
			 o.isActive = true;
			 //选项卡激活执行以下代码
			 if(o.initFlag){
				 o.initFlag=false; //重置初始化状态
				 return;
			 }
			 this.chart.initialDataSet=false;//关键
			 //判断是否有更新
			 if(this.isUpdate) {
				 this.showMask();
				 this.loadChartXml(this,true);
				 this.isUpdate=false;
			 }else{
				 o.showMask();
				 o.chart.setDataXML(o.data_xml);
				 o.chart.render(o.body.id+"_chart_tu");
				 o.hideMask();
			 }
	 	 },deactivate : function(o){
	 		 o.isActive = false;
	 	 }
	 },
	 crack:'?a=fusioncharts.com&PBarLoadingText=图形加载中,请稍等...&XMLLoadingText=图形加载中,请稍等...&ParsingDataText=图形加载中,请稍等...&RenderingChartText=图形加载中,请稍等...&LoadDataErrorText=没有符合条件的数据&InvalidXMLText=没有符合条件的数据&ChartNoDataText=没有符合条件的数据'
});
Ext.reg('xchart', Ext.ux.ChartPanel);